'use strict';

module.exports = function(server) {
  // Install a `/` route that returns server status
  var router = server.loopback.Router();
  router.get('/', server.loopback.status());

  router.post('/login', function(req, res) {
    if (!req.body) return res.send('The API service exceptions.');
    // define user info for login.
    var userLoginInfo = {
      username: req.body.username,
      password: req.body.password,
    };
    // Execute login
    var SysUser = server.models.SysUser;
    SysUser.login(userLoginInfo, 'user', function(err, token) {
        // Login failed.
      if (err) {
          return res.status(401).send({
            userName: userLoginInfo.username,
            permissionFailed: true,
            msg: 'Authentication failed, you do not have permission！',
          });
        }
        // Login success.
      token = token.toJSON();
      res.send({
          userId: token.userId,
          userName: token.user.username,
          userEmail: token.user.email,
          token: token.id,
        });
    });
  });

  router.post('/logout', function(req, res) {
    if (!req.body || !req.query) return res.send('The API service exceptions.');
    // Get token
    var destroyToken = req.body.token || req.query['token'];
    // Execute logout
    var SysUser = server.models.SysUser;
    SysUser.logout(destroyToken, function(err) {
      if (err) {
        return res.status(403).send({
          destroyFailed: true,
          msg: err,
        });
      } else {
        return res.send();
      }
    });
  });

  server.use(router);
};
